import 'package:loxen/mode/mine/mine_comment_bean.dart';
import 'package:loxen/mode/mine/mine_msg_bean.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:flutter/foundation.dart';
import 'package:loxen/api/api.dart';
import 'package:rxdart/rxdart.dart';

class MineMsgViewModel extends BaseViewModel {
  Map<String, List<MineMsg>> _map = {};

  //加载数据
  void loadData() {
    ApiService.userMsgs()
        .doOnListen(() {
          mState = BaseState.LOADING;
        })
        .flatMap((value) => compute(decodeMineMsgBeanData, value.data).asStream())
        .listen((event) {
         if(event.data.results.length > 0){
           _map.putIfAbsent('0', () => event.data.results);
           mState = BaseState.CONTENT;
           print('消息通知');
           print(event.data.toJson());

         }else{
           mState = BaseState.EMPTY;
         }
        }, onError: (error, stackTrace) {
          mState = BaseState.FAIL;
          print(error);
          print(stackTrace);
        }, onDone: () => notifyListeners());
  }

  // 加载下一页数据
  Future<List<MineMsg>> nextData(int page) async {
    if (_map.containsKey(page.toString())) {
      return _map[page.toString()];
    } else {
      var data = await ApiService.userMsgs(page: (page += 1).toString())
          .flatMap((value) => compute(decodeMineMsgBeanData, value.data).asStream())
          .first;
      _map.putIfAbsent(page.toString(), () => data.data.results);
      return data.data.results;
    }
  }

  //刷新列表内容
  void refresh() {
    _map.clear();
  }

  static MineMsgBean decodeMineMsgBeanData(dynamic json) {
    return MineMsgBean.fromJson(json);
  }
}
